import base64
import hashlib
import time

import rsa
import yaml

from commons.base_url_util import read_ini
from configs import setting


class DebugTalk:
    # 读取
    def read_yaml(self,k):
        with open(setting.extract_name,encoding="utf-8") as f:
            value = yaml.safe_load(f)
            return value[k]

    # 读取环境变量
    def env(self,key):
        return read_ini()[key]

    # md5加密
    def md5_encode(self,data):
        # 将数据转换为utf-8的编码格式
        data = str(data).encode("utf-8")
    #     md5加密，哈希算法
        md5_value = hashlib.md5(data).hexdigest()
        return md5_value

    # base64_encode加密
    def base64_encode(self,data):
        # 将数据转换为utf-8的编码格式
        data = str(data).encode("utf-8")
        # base64加密
        base64_value = base64.b64encode(data).decode("utf-8")
        return base64_value

    def get_random_number(self):
        return str(int(time.time()))

#     生成RSA的公钥和私钥
    def creat_RSA_key(self):
        (public_key,private_key) = rsa.newkeys(1024)
        with open("./public.pem", "w+") as f:
            f.write(public_key.save_pkcs1().decode())
        with open("./private.pem", "w+") as f:
            f.write(private_key.save_pkcs1().decode())

#     加密RSA
    def rsa_encode(self,data):
        # 加载公钥
        with open("./public.pem") as f:
            pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
        # 将数据转换为utf-8的编码格式
        data = str(data).encode("utf-8")
        # 把字符串加密成byte类型
        byte_value = rsa.encrypt(data, pubkey)
        # 把字节转换成字符串格式
        rsa_value = base64.b64encode(byte_value).decode("utf-8")
        return  rsa_value

if __name__ == '__main__':
    admin_md5 = DebugTalk().md5_encode("admin")
    print(admin_md5)
    if admin_md5 == '21232f297a57a5a743894a0e4a801fc3':
        print("admin_md5 is success")
    admin_base64 = DebugTalk().base64_encode("admin")
    print(admin_base64)
    if admin_base64 == 'YWRtaW4=':
        print("admin_base64 is success")
    DebugTalk().creat_RSA_key()
    print("--------RSA---------")
    print(DebugTalk().rsa_encode("admin"))

